import 'package:boss/common/common.dart';


import 'package:boss/main.dart';
import 'package:boss/provider/version_provider.dart';
import 'package:boss/ui/widget/app_version_up.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class VersionUtil {
  static bool isWorking = false;

  static checkVersion(BuildContext context, {bool isNeedToast = true}) async {
    try {
      if (isWorking) return;

      isWorking = true;
      var versionProvider = Provider.of<VersionProvider>(
        context,
        listen: false,
      );
      versionProvider.setRedDot(false);

      var response = await api.getVersion(Constant.uuid);

      if (!response.successful()) {
        toast(response.msg);
        return;
      }

      var prodVersion = int.parse(response.data.version.replaceAll('.', ''));
      var currentVersion = int.parse(Constant.appVersion.replaceAll('.', ''));

      var isNeedUpdated = prodVersion > currentVersion;

      if (isNeedUpdated) {
        showAppVersionUpModal(
          context,
          version: response.data.version,
          content: response.data.versionExternal,
          forceUpdate: response.data.forceUpdate == 0,
          downloadUrl: response.data.packages,
        );
      } else {
        if (isNeedToast) toast('当前已是最新版本');
      }
    } catch (e) {
      toast(Constant.httpServeErrText);
    } finally {
      isWorking = false;
    }
  }
}
